package jsu.xnm.pantry.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jsu.xnm.pantry.bean.Employee;
import jsu.xnm.pantry.exception.CustomException;
import jsu.xnm.pantry.mapper.EmployeeMapper;
import jsu.xnm.pantry.service.EmployeeService;
import jsu.xnm.pantry.utils.JwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class EmployeeIServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Resource
    private JwtUtil jwtUtil;

    @Override
    public void saveEmployee(Employee employee) {
        employee.setPassword(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()));
        this.save(employee);
    }

    @Override
    public String authenticateUser(String username, String password) {
        //根据用户名查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(Employee::getUsername, username);

        Employee employee = this.getOne(queryWrapper);

        /*过关斩将*/
        // 用户不存在或密码不匹配，抛出异常
        if (employee == null) {
            throw new CustomException("用户不存在");
        }
        //密码校验
        if(!password.equals(employee.getPassword())){
            throw new CustomException("密码错误");
        }
        //账号状态校验
        if(employee.getStatus() == 0){
            throw new CustomException("账号已禁用");
        }
        // 用户认证通过，生成 JWT Token
        return jwtUtil.generateToken(Long.valueOf(employee.getId()), employee.getUsername());
    }
}